import os
import re

kasan_log_key_1 = "BUG: KASAN:"
kasan_log_key_2 = "==================="
kasan_type = ["global-out-of-bounds","stack-out-of-bounds","use-after-free","wild-memory-access on dddress","slab-out-of-bounds"]
kasan_result = "./result"

# 比较判断字符串是否存在
def is_in(full_str,sub_str):
    if re.findall(sub_str,full_str):
        return True
    else:
        return False
#单列数据内容写入文件
def writedata(data,filename):
    with open(os.path.join(kasan_result,filename),"w") as f:
        f.writelines(data)
#确定故障文件名称
def getlogname(data):
    name = "";
    for type in kasan_type:
        if is_in(data,type):
            name = type
            break
    if len(name)==0 :
        name = "未知类型"
    return name+data.split("in",1)[1].replace("\n","").replace("/","_").replace(" ","")
def openfile(filename):
    with open (filename,'r',encoding='utf-8') as f :
        iskasan = False
        kasanlog = []
        index = 1
        kasanlogfilename = ""
        for line in f :
            if is_in(line,kasan_log_key_1) :
                iskasan = True
                kasanlogfilename = getlogname(line);
            if iskasan:
                kasanlog.append(line)
            if iskasan and is_in(line,kasan_log_key_2):
                iskasan = False
                if not os.path.exists(kasan_result):
                    os.mkdir(kasan_result);
                writedata(kasanlog,"kasan_"+str(index)+"_"+kasanlogfilename);
                index +=1;
                kasanlog.clear();

#解析目录中以“hilog_kmsg.”开头的日志文件
def parsekmsglog():
    names = [name for name in os.listdir("./") if name.startswith('hilog_kmsg.')]
    for name in names :
        openfile(name)



# 功能：解析kmsg日志中的kasan故障，并将故障日志输出到result文件夹下。
# 使用：将设备data/log/hilog 中导出的以hilog_kmsg开头的日志解压到当前目录下，cmd到当前目录下，执行 python parsekmsgforkasan.py
#      指令后，在result文件夹下生成已kasan_i_type_函数名称+地址的kasan故障日志
if __name__ == '__main__':
    parsekmsglog()

